package hou.just4fun.DownloadNetEaseMusic.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author houweitao
 * @date 2016年6月6日上午11:34:38
 */

public class DecodeD_baseMD5 {
	private static Map<Character, String> map;

	public static void main(String[] args) {
		DecodeD_baseMD5 db = new DecodeD_baseMD5();
		db.init();
	}

	private void init() {
		map = makeHashMap();
		System.out.println(map.size());
		System.out.println(ten2two("05"));

		System.out.println(decode("d+1Jmjcbqdu3q7N3Mfx7+g"));
	}

	public String decode(String str) {
		List<String> list = new ArrayList<>();
		for (int i = 0; i < str.length(); i++) {
			list.add(map.get(str.charAt(i)));
		}

		StringBuffer sb = new StringBuffer();
		for (String s : list) {
			sb.append(ten2two(s));
		}

		String perpare = sb.substring(0, sb.length() - 4);

		return helpDecode(perpare).toUpperCase();
	}

	private String helpDecode(String str) {
		System.out.println(str);

		if (str.length() % 8 != 0)
			return null;
		StringBuffer ret = new StringBuffer();
		int size = str.length() / 8;
		for (int i = 0; i < size; i++) {
			String cur = str.substring(8 * i, 8 * i + 8);
			int curInt = Integer.valueOf(Integer.valueOf(cur, 2).toString());
			// System.out.println(curInt);
			String hex = Integer.toHexString(curInt);
			ret.append(hex);
			// ret.append(",");
		}
		return ret.toString();
	}

	private Map<Character, String> makeHashMap() {
		Map<Character, String> ret = new HashMap<>();

		for (char i = 'A'; i <= 'Z'; i++) {
			ret.put(i, uniform(i - 'A'));
		}

		for (char i = 'a'; i <= 'z'; i++) {
			ret.put(i, uniform(26 + (i - 'a')));
		}
		for (char i = '0'; i <= '9'; i++) {
			ret.put(i, uniform(52 + (i - '0')));
		}

		ret.put('+', "62");
		ret.put('/', "63");

		return ret;
	}

	private String uniform(int num) {
		if (num < 0)
			return "";
		else if (num < 10)
			return "0" + num;
		else
			return num + "";
	}

	private String ten2two(String str) {
		int in = Integer.valueOf(str);
		String ret = Integer.toBinaryString(in);

		int need = 6 - ret.length();

		for (int i = 0; i < need; i++)
			ret = 0 + ret;

		return ret;
	}
}
